package com.project.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImp implements IUserService {
    @Autowired
    private IUserMapper mapper;

    @Override
    public UserBean login(String userName, String password) {
        QueryWrapper qw =new QueryWrapper<>();
        qw.eq("u_userName",userName);
        qw.eq("u_password",password);
        UserBean userBean = mapper.selectOne(qw);
        if(userBean != null){
            List<GradeBean> gradeBeanList = mapper.findById(userBean.getId());
            userBean.setGradeList(gradeBeanList);
        }
        return userBean;
    }

    @Override
    public IPage<UserBean> cutByItem(Integer pageNO, String userName) {
        QueryWrapper qw =new QueryWrapper<>();
        if (userName!=null&&!userName.equals("")) {
            qw.like("u_userName", userName);
        }
        return mapper.selectPage(new Page<>(pageNO,5),qw);
    }

    @Override
    public void add(String userName, String name, Integer[] roleIdArray) {
        UserBean userBean = new UserBean(userName,name);
        mapper.insert(userBean);
        mapper.addUserRole(userBean.getId(),roleIdArray);
    }

    @Override
    public void del(Integer userId) {
        mapper.delUserRole(userId);
        mapper.deleteById(userId);
    }

    @Override
    public UserBean findByUserId(Integer userId) {
        return mapper.findByUserId(userId);
    }


    @Override
    public void updatePassword(Integer userId, String newPassword) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("pk_userId",userId);
        UserBean userBean=mapper.selectOne(qw);
        userBean.setPassword(newPassword);
        mapper.updateById(userBean);
    }
}
